<template>
	<div class="relative">
		<div class="absolute top-[5%] right-4">
			<el-space>
				<div
					v-for="item in labelList"
					:class="{
						label_bg: true,
						active: item.label === currentLabel,
					}"
					@click="handleClick(item.label)"
					:key="item.label"
				>
					{{ item.label }}
				</div>
			</el-space>
		</div>
		<div ref="chartRef" class="w-full h-full min-h-[160px]"></div>
	</div>
</template>

<script setup lang="ts">
import { tryOnUnmounted, useDebounceFn } from '@vueuse/core';
import * as echarts from 'echarts';
import { useEventListener } from '/@/hooks/event/useEventListener';
const labelList = [
	{
		label: 'CO',
	},
	{
		label: 'SO₂',
	},
	{
		label: 'NO₂',
	},
	{
		label: 'PM10',
	},
	{
		label: 'PM2.5',
	},
	{
		label: 'O₃',
	},
];
const chartRef = ref();
let resizeFnChain = resize;
let removeResizeFn = () => {};
let instance: any;
const currentLabel = ref('CO');
const seriesData = ref<number[]>([]);
resizeFnChain = useDebounceFn(resize, 200);
const handleClick = (l: string) => {
	currentLabel.value = l;
	getData(true);
};
const getData = (enale = false) => {
	let list = [];
	for (let i = 0; i < 23; i++) {
		const item = Math.floor(Math.random() * 30) - 15;
		list.push(item);
	}
	seriesData.value = list;
	enale &&
		instance.setOption({
			series: [
				{
					data: list,
				},
			],
		});
	console.log('111');
};
const setOptions = () => {
	instance = echarts.init(chartRef.value);
	getData();
	console.log('222');
	const option = {
		color: '#0b5fd4',
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'line',
				axis: 'x',
			},
		},
		grid: {
			left: 4,
			right: 10,
			bottom: 0,
			top: 40,
			containLabel: true,
		},
		xAxis: {
			type: 'category',
			name: '时间',
			axisLabel: { color: '#fff', fontSize: 10 },

			axisTick: {
				alignWithLabel: true,
			},
			data: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8],
		},
		yAxis: {
			type: 'value',
			name: '增长率',
			nameTextStyle: { color: '#fff', fontSize: 12 },
			axisLabel: { color: '#fff', fontSize: 10, formatter: '{value}%' },
		},
		series: [
			{
				type: 'bar',
				name: '环比增长率',
				data: seriesData.value,
			},
		],
	};
	instance.setOption(option);
	const { removeEvent } = useEventListener({
		el: window,
		name: 'resize',
		listener: resizeFnChain,
	});
	removeResizeFn = removeEvent;
};
function resize() {
	const config = {
		animation: {
			duration: 200,
			easing: 'quadraticIn',
		},
	};
	instance.resize(config);
}
onMounted(() => {
	setOptions();
});

tryOnUnmounted(() => {
	removeResizeFn();
});
</script>

<style lang="scss" scoped>
.label_bg {
	font-size: 12px;
	line-height: 14px;
	padding: 2px;
	border-radius: 2px;
	font-weight: 100;
	cursor: pointer;
	user-select: none;
	box-shadow: 0px 0px 3px 2px rgba(33, 107, 245, 0.5) inset;
	&.active {
		box-shadow: 0px 0px 3px 2px rgba(59, 210, 236, 0.5) inset;
	}
}
</style>
